package pers.karl.security.service.impl;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import pers.karl.security.entity.Authentication;
import pers.karl.security.service.AuthenticationService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author karl
 * @description:
 * @create 2020-08-11 09:38
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    private List<Authentication> authentications;

    public AuthenticationServiceImpl() {

        int size = 3;
        authentications = new ArrayList<>(size);

        Authentication authentication = null;

        authentication = new Authentication();
        authentication.setUsername("admin");
        authentication.setPassword("{noop}admin");
        authentication.setEnabled(true);
        authentications.add(authentication);

        for (int i = 0, len = size - 1; i < len; i++) {
            authentication = new Authentication();
            authentication.setUsername("user" + i);
            authentication.setPassword("{noop}pwd" + i);
            authentication.setEnabled(true);
            authentications.add(authentication);
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!StringUtils.hasText(username)) {
            throw new UsernameNotFoundException("username is invalid");
        }

        for (Authentication authentication : authentications) {
            if (authentication.getUsername().equals(username)) {
                return new User(authentication.getUsername(), authentication.getPassword(), authentication.isEnabled(),
                        true, true, true, AuthorityUtils.NO_AUTHORITIES);
            }
        }

        throw new UsernameNotFoundException("username not found");
    }

}
